package com.ctsi.question.controller;

import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.exception.ExceptionFactory;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.offlinesupport.service.ProjectEntityService;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.Person;
import com.ctsi.organise.entity.OrganiseEntity;
import com.ctsi.organise.service.OrganiseEntityManager;
import com.ctsi.organise.service.PersonEntityManager;
import com.ctsi.question.dto.*;
import com.ctsi.question.entity.WeekReportDetailEntity;
import com.ctsi.question.entity.WeekReportEntity;
import com.ctsi.question.service.NextPlanEntityService;
import com.ctsi.question.service.WeekReportDetailEntityService;
import com.ctsi.question.service.WeekReportEntityService;
import com.ctsi.supportflow.app.entity.ProjectEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class WeekReportController {

    @Autowired
    private WeekReportEntityService weekReportEntityService;
    @Autowired
    private PersonServiceProxy personServiceProxy;
    @Autowired
    private OrganiseEntityManager organiseEntityManager;
    @Autowired
    private PersonEntityManager personEntityManager;
    @Autowired
    private WeekReportDetailEntityService weekReportDetailEntityService;
    @Autowired
    private NextPlanEntityService nextPlanEntityService;
    @Autowired
    private ExceptionFactory exceptionFactory;
    @Autowired
    private ProjectEntityService projectEntityService;

    /**
     * 填写周报,生成主表
     * @param reportType 周报类型 0 周报 1双周报
     * @param selectTime
     * @return
     */
    @PostMapping(value = "/week-report/submit-report")
    public UnifiedResponse<WeekReportEntity> addReport(@RequestParam(value = "reportType") Integer reportType,
                                                       @RequestParam(value = "selectTime",required = false) String selectTime) {
        String userId = SecurityUtil.getUser().getUserId();
        long curTime = System.currentTimeMillis();
        if (UtilValidate.isNotEmpty(selectTime)) {
            curTime = UtilDateTime.toLong(selectTime);
        }
        Person person = personServiceProxy.findPersonById(userId);
        long begin = UtilDateTime.getDayBeginTimeInWeek(new Date(curTime),1);
        long curWeekEnd = UtilDateTime.getDayBeginTimeInWeek(new Date(curTime), 5);
        String title=UtilDateTime.longToString(begin,UtilDateTime.defaultDatePattern)+"至"+UtilDateTime.longToString(curWeekEnd,UtilDateTime.defaultDatePattern);
//        String title = UtilDateTime.longToString(curWeekEnd, UtilDateTime.defaultDatePattern);
        WeekReportEntity reportEntity = weekReportEntityService.isExit(title, reportType, userId);
        if (reportEntity == null) {
            // 生成周报
            reportEntity = new WeekReportEntity();
            reportEntity.setWeekReportType(reportType);
            reportEntity.setSubmitorId(userId);
            reportEntity.setSubmitorName(person.getFullName());
            Organise organise = personEntityManager.getUserDefaultOrgan(userId);
            String organId = organise.getPartyId();
            reportEntity.setDepartId(organId);
            List<OrganiseEntity> organChain = organiseEntityManager.getOrganiseChain(organId);
            reportEntity.setDepartName(organChain.stream().map(chain -> UtilValidate.isNotEmpty(chain.getShortName()) ? chain.getShortName() : chain.getOrganiseName()).collect(Collectors.joining(" > ")));
            reportEntity.setReportTime(curTime);
            reportEntity.setReportTitle(title);
            weekReportEntityService.insertWeekReportEntity(reportEntity);
        }
        return UnifiedResponse.ok(reportEntity);
    }

    /**
     * 分页获取周报信息
     *
     * @param pageNo
     * @param pageSize
     * @param reportType
     * @return
     */
    @PostMapping(value = "/week-report/report-page")
    public UnifiedResponse<Page<WeekReportDTO>> queryReportPage(@RequestParam("pageNo") Integer pageNo,
                                                                @RequestParam("pageSize") Integer pageSize,
                                                                @RequestParam(value = "reportType",required = false) Integer reportType) {
        String userId = SecurityUtil.getUser().getUserId();
        return UnifiedResponse.ok(weekReportEntityService.findReportPage(reportType, userId, pageNo, pageSize));
    }

    /**
     * 根据当前登陆用户查询所有的项目，供APP选择使用
     * @return
     */
    @PostMapping(value = "/week-report/find-projects")
    public UnifiedResponse<List<Map<String,Object>>> findProjectByCurUserId(){
        String userId = SecurityUtil.getUser().getUserId();
        return UnifiedResponse.ok(weekReportEntityService.findProjectsByUserId(userId));
    }

    /**
     * 本周工作详情
     *
     * @param reportId
     * @return
     */
    @PostMapping(value = "/week-report/cur-report-details")
    public UnifiedResponse<List<WeekReportDetailDTO>> findReportDetails(@RequestParam("reportId") String reportId) {
        String userId = SecurityUtil.getUser().getUserId();
        WeekReportEntity report = weekReportEntityService.findWeekReportEntityById(reportId);
        long reportTime = report.getReportTime();
        long begin = UtilDateTime.getDayBeginTimeInWeek(new Date(reportTime),1);
        long end = UtilDateTime.getDayBeginTimeInWeek(new Date(reportTime),5);
        List<WeekReportDetailDTO> result = weekReportDetailEntityService.details(reportId, null);
        result.forEach(details -> details.setReportDetailTitle(UtilDateTime.longToString(begin,UtilDateTime.defaultDatePattern)+"至"+UtilDateTime.longToString(end,UtilDateTime.defaultDatePattern)));
        return UnifiedResponse.ok(result);
    }

    /**
     * 查询周报详情
     * @param detailId  1568649600000
     * @return
     */
    @PostMapping(value = "/week-report/report-detail")
    public UnifiedResponse<WeekReportDetailDTO> findReportDetail(@RequestParam("detailId") String detailId){
        String userId = SecurityUtil.getUser().getUserId();
        WeekReportDetailEntity entity = weekReportDetailEntityService.findWeekReportDetailEntityById(detailId);
        WeekReportEntity report = weekReportEntityService.findWeekReportEntityById(entity.getWeekReportId());
        long reportTime = report.getReportTime();
        long begin = UtilDateTime.getDayBeginTimeInWeek(new Date(reportTime),1);
        long end = UtilDateTime.getDayBeginTimeInWeek(new Date(reportTime),5);
        WeekReportDetailDTO dto = weekReportDetailEntityService.detail(detailId, null);
        dto.setReportDetailTitle(UtilDateTime.longToString(begin,UtilDateTime.defaultDatePattern)+"至"+UtilDateTime.longToString(end,UtilDateTime.defaultDatePattern));
        return UnifiedResponse.ok(dto);
    }

    /**
     * 查询主表详情
     */
    @PostMapping(value = "/week-report/primary-report-details")
    public UnifiedResponse<WeekReportEntity> findReportPrimaryDetails(@RequestParam("id") String id) {
        WeekReportEntity weekReportEntity = weekReportEntityService.editWeekReportEntityById(id);
        weekReportEntity.setReportTime(weekReportEntity.getReportTime());
        return UnifiedResponse.ok(weekReportEntity);
    }

    /**
     * 用户项目选择
     *
     * @return
     */
    @PostMapping(value = "/week-report/report-projects")
    public UnifiedResponse<List<ReportProjectDTO>> findNeedReportItems() {
        String userId = SecurityUtil.getUser().getUserId();
        return UnifiedResponse.ok(weekReportDetailEntityService.findReportProjects(userId));
    }

    /**
     * 判断当前是否延期
     *
     * @param projectCode    项目ID
     * @param curProjectRate 当前用户输入的项目进度
     * @return
     */
    @PostMapping(value = "/week-report/is-delay")
    public UnifiedResponse<Map<String, Integer>> isDelay(@RequestParam("projectCode") String projectCode,
                                                         @RequestParam("curProjectRate") Integer curProjectRate) {
        ProjectEntity projectEntity = new ProjectEntity();
        projectEntity.setId(projectCode);
        Map<String, Integer> result = new HashMap<>();
        result.put("isDelay", 0);
        ProjectStageInfo stageInfo = weekReportDetailEntityService.findProjectStageInfo(SecurityUtil.getUser().getUserId(), projectCode);
        if (stageInfo != null) {
            Integer rate = stageInfo.getPlanSpeed();
            Long end = stageInfo.getEndTime();
            if (rate != null && end != null) {
                end = UtilDateTime.getDayStart(new Date(stageInfo.getEndTime()));
                if (curProjectRate < rate && UtilDateTime.getDayBeginTimeInWeek(new Date(),5) >= end) {
                    result.put("isDelay", 1);
                    projectEntity.setProjectStatus(2);
                    projectEntityService.updateProjectEntityByPKSelective(projectEntity);
                    return UnifiedResponse.ok(result);
                }
            }

        }
        if (curProjectRate == 100) {
            projectEntity.setProjectStatus(3);
//            projectEntity.setEndTime(System.currentTimeMillis());
        } else {
            projectEntity.setProjectStatus(1);
        }
        projectEntityService.updateProjectEntityByPKSelective(projectEntity);
        return UnifiedResponse.ok(result);
    }

    /**
     * 添加周报详情
     *
     * @param addReportDetails
     * @return
     */
    @PostMapping(value = "/week-report/add-report-details")
    public UnifiedResponse<Void> addReportDetails(@RequestBody AddReportDetails addReportDetails) {
        String jobType = addReportDetails.getJobType();
        if (jobType.equals("tempReportType")) {
            // 临时工作
            WeekReportDetailEntity detailEntity = addReportDetails.toWeekReportDetailEntity(false);
            weekReportDetailEntityService.insertWeekReportDetailEntity(detailEntity);
        } else if (jobType.equals("projectReportType")) {
            // 项目
            String projectCode = addReportDetails.getProjectCode();
            if (UtilValidate.isEmpty(projectCode)) {
                exceptionFactory.throwDefinedException("params-error", "项目ID不能为空!");
            }
            ProjectStageInfo stageInfo = weekReportDetailEntityService.findProjectStageInfo(SecurityUtil.getUser().getUserId(), projectCode);
            boolean isCharge = stageInfo != null && stageInfo.getIsCharge() != null && stageInfo.getIsCharge() == 1;
            WeekReportDetailEntity detailEntity = addReportDetails.toWeekReportDetailEntity(isCharge);
            weekReportDetailEntityService.insertWeekReportDetailEntity(detailEntity);
        } else {
            exceptionFactory.throwDefinedException("params-error", "未知的工作类型!");
        }
        return UnifiedResponse.ok();
    }

    /**
     * 删除本周工作详情
     *
     * @param detailId
     * @return
     */
    @PostMapping(value = "/week-report/del-report-details")
    public UnifiedResponse<Integer> delReportDetails(@RequestParam("detailId") String detailId) {
        int i = weekReportDetailEntityService.removeWeekReportDetailEntity(detailId);
        return UnifiedResponse.ok(i);
    }

    /**
     * 更新周报
     * @param addReportDetails
     * @return
     */
    @PostMapping(value = "/week-report/update-details")
    public UnifiedResponse<Void> updateReportDetails(@RequestBody AddReportDetails addReportDetails) {
        String jobType = addReportDetails.getJobType();
        if (jobType.equals("tempReportType")) {
            WeekReportDetailEntity detailEntity = addReportDetails.toWeekReportDetailEntity(false);
            weekReportDetailEntityService.updateWeekReportDetailEntityByPKSelective(detailEntity);
        } else if (jobType.equals("projectReportType")) {
            // 项目
            String projectCode = addReportDetails.getProjectCode();
            if (UtilValidate.isEmpty(projectCode)) {
                exceptionFactory.throwDefinedException("params-error", "项目ID不能为空!");
            }
            ProjectStageInfo stageInfo = weekReportDetailEntityService.findProjectStageInfo(SecurityUtil.getUser().getUserId(), projectCode);
            boolean isCharge = stageInfo != null && stageInfo.getIsCharge() != null && stageInfo.getIsCharge() == 1;
            WeekReportDetailEntity detailEntity = addReportDetails.toWeekReportDetailEntity(isCharge);
            weekReportDetailEntityService.updateWeekReportDetailEntityByPKSelective(detailEntity);
        }
//        String projectCode = addReportDetails.getProjectCode();
//        if (UtilValidate.isEmpty(projectCode) || UtilValidate.isEmpty(addReportDetails.getId())) {
//            exceptionFactory.throwDefinedException("params-error", "参数错误!");
//        }
//        ProjectStageInfo stageInfo = weekReportDetailEntityService.findProjectStageInfo(SecurityUtil.getUser().getUserId(), projectCode);
//        boolean isCharge = stageInfo.getIsCharge() == 1;
//        WeekReportDetailEntity detailEntity = addReportDetails.toWeekReportDetailEntity(isCharge);
//        weekReportDetailEntityService.updateWeekReportDetailEntityByPKSelective(detailEntity);
        return UnifiedResponse.ok();
    }


    /**
     * 下周工作计划
     *
     * @param reportId
     * @return
     */
    @PostMapping(value = "/week-report/next-report-details")
    public UnifiedResponse<List<NextPlanDTO>> findNextPlanDetails(@RequestParam("reportId") String reportId) {
        String userId = SecurityUtil.getUser().getUserId();
        List<NextPlanDTO> result = nextPlanEntityService.findNextPlanDetails(reportId, null);
        WeekReportEntity report = weekReportEntityService.findWeekReportEntityById(reportId);
        long reportTime = report.getReportTime();
        long begin = UtilDateTime.getDayBeginTimeInWeek(new Date(reportTime),1);
        long end = UtilDateTime.getDayBeginTimeInWeek(new Date(reportTime),5);
        result.stream().forEach(re -> {
            re.setTitle(UtilDateTime.longToString(begin,UtilDateTime.defaultDatePattern)+"至"+UtilDateTime.longToString(end,UtilDateTime.defaultDatePattern));
        });
        return UnifiedResponse.ok(result);
    }

    /**
     * 计划详情
     */
    @PostMapping(value = "/week-report/weekReportPlanDetail")
    public UnifiedResponse<NextPlanDTO> WeekReportPlanDetail(@RequestParam("planId") String planId) {
        NextPlanDTO planDetails = nextPlanEntityService.findPlanDetails(planId, null);
        return UnifiedResponse.ok(planDetails);
    }
    /**
     * 删除工作计划
     *
     * @param planId
     * @return
     */
    @PostMapping(value = "/week-report/del-next-plan")
    public UnifiedResponse<Integer> delNextPlan(@RequestParam("planId") String planId) {
        int i = nextPlanEntityService.removeNextPlanEntity(planId);
        return UnifiedResponse.ok(i);
    }

    /**
     * 添加下周工作计划
     *
     * @param addNextPlanDTO
     * @return
     */
    @PostMapping(value = "/week-report/add-next-plan")
    public UnifiedResponse<Void> addNextPlan(@RequestBody AddNextPlanDTO addNextPlanDTO) {
        nextPlanEntityService.insertNextPlanEntity(addNextPlanDTO.toNextPlanEntity());
        return UnifiedResponse.ok();
    }

    /**
     * 更新下周工作计划
     *
     * @param addNextPlanDTO
     * @return
     */
    @PostMapping(value = "/week-report/update-next-plan")
    public UnifiedResponse<Void> updateNextPlan(@RequestBody AddNextPlanDTO addNextPlanDTO) {
        if (UtilValidate.isEmpty(addNextPlanDTO.getId())) {
            exceptionFactory.throwDefinedException("params-error", "参数错误！");
        }
        nextPlanEntityService.updateNextPlanEntityByPKSelective(addNextPlanDTO.toNextPlanEntity());
        return UnifiedResponse.ok();
    }

    // ******************************************************工作督察*************************************************************

    /**
     * 周报，双周报列表
     *
     * @param pageNo
     * @param pageSize
     * @param queryTime
     * @param reportType
     * @return
     */
    @PostMapping(value = "/week-report/supervision-list")
    public UnifiedResponse<Map<String, Object>> findSupervisionList(@RequestParam("pageNo") Integer pageNo,
                                                                    @RequestParam("pageSize") Integer pageSize,
                                                                    @RequestParam(value = "queryTime", required = false) String queryTime,
                                                                    @RequestParam(value = "reportType",required = false) Integer reportType) {
        String userId = SecurityUtil.getUser().getUserId(); // 当前用户ID
        Long queryTim = null;
        if (UtilValidate.isNotEmpty(queryTime)) {
            queryTim = UtilDateTime.toLong(queryTime);
        } else {
            queryTim = System.currentTimeMillis();
        }
        Page<SupervisionDTO> pages = weekReportEntityService.findSupervisionDTO(userId, reportType, queryTim, pageNo, pageSize);
        Map<String, Object> result = new HashMap<>();
        long curWeekEnd = UtilDateTime.getDayBeginTimeInWeek(new Date(queryTim), 5);
        String title = UtilDateTime.longToString(curWeekEnd, UtilDateTime.defaultDatePattern);
        result.put("title", title);
        result.put("result", pages);
        return UnifiedResponse.ok(result);
    }

//    /**
//     * 通过人员ID和时间，查看周报详情
//     * @param personId
//     * @param reportType
//     * @param reportTime
//     * @return
//     */
//    @PostMapping(value = "/week-report/person-report-details")
//    public UnifiedResponse<List<WeekReportDetailEntity>> findPersonReport(@RequestParam("personId") String personId,
//                                                  @RequestParam("reportType") Integer reportType,
//                                                  @RequestParam("reportTime") String reportTime){
//
//
//        return null;
//    }

    /**
     * 针对周报详情的评价
     *
     * @param detailId
     * @param eval
     * @param evalContent
     * @return
     */
    @PostMapping(value = "/week-report/eval-detail")
    public UnifiedResponse<Void> evalSingle(@RequestParam("detailId") String detailId,
                                            @RequestParam("eval") String eval,
                                            @RequestParam("evalContent") String evalContent) {
        WeekReportDetailEntity detailEntity = new WeekReportDetailEntity();
        detailEntity.setId(detailId);
        detailEntity.setLeaderEval(eval);
        detailEntity.setLeaderApproval(evalContent);
        detailEntity.setLeaderApprovalTime(System.currentTimeMillis());
        weekReportDetailEntityService.updateWeekReportDetailEntityByPKSelective(detailEntity);
        return UnifiedResponse.ok();
    }

    /**
     * 针对整个周报进行评价
     *
     * @param reportId
     * @param eval
     * @param evalContent
     * @return
     */
    @PostMapping(value = "/week-report/eval-report")
    public UnifiedResponse<Integer> evalReport(@RequestParam("reportId") String reportId,
                                            @RequestParam("eval") String eval,
                                            @RequestParam("evalContent") String evalContent) {
        WeekReportEntity report = new WeekReportEntity();
        report.setId(reportId);
        report.setLeaderApproval(evalContent);
        report.setLeaderApprovalTime(System.currentTimeMillis());
        report.setLeaderEval(eval);
        int i = weekReportEntityService.updateWeekReportEntityByPKSelective(report);
        return UnifiedResponse.ok(i);
    }

    /**
     * 员工状态统计分析
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/week-report/person-analysis")
    public UnifiedResponse<Page<PersonAnalysisDTO>> personInfo(@RequestParam("pageNo") Integer pageNo,
                                                               @RequestParam(value = "personName",required = false) String personName,
                                                               @RequestParam("pageSize") Integer pageSize) {
        String userId = SecurityUtil.getUser().getUserId();
        String personNameLike = null;
        if (UtilValidate.isNotEmpty(personName)) {
            personNameLike = "%" + personName + "%";
        }
        Page<PersonAnalysisDTO> result = weekReportEntityService.findPersonAnalysis(userId, personNameLike, pageNo, pageSize);
        return UnifiedResponse.ok(result);
    }

    /**
     * 员工的项目情况分析
     *
     * @param personId
     * @param projectName
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/week-report/person-projects")
    public UnifiedResponse<Page<PersonProjectDTO>> personProjects(@RequestParam("personId") String personId,
                                                                  @RequestParam(value = "projectName", required = false) String projectName,
                                                                  @RequestParam("pageNo") Integer pageNo,
                                                                  @RequestParam("pageSize") Integer pageSize) {
        String projectNameLike = null;
        if (UtilValidate.isNotEmpty(projectName)) {
            projectNameLike = "%" + projectName + "%";
        }
        return UnifiedResponse.ok(weekReportEntityService.findPersonProjects(personId, projectNameLike, pageNo, pageSize));
    }

    /**
     * 查看项目详情
     * @param projectId
     * @return
     */
    @PostMapping(value = "/week-report/project-info")
    public UnifiedResponse<ProjectPlanInfo> projectInfos(@RequestParam("projectId") String projectId) {
        return UnifiedResponse.ok(weekReportEntityService.findProjectInfo(projectId));
    }

    /**
     * 项目统计分析
     * @param projectName
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/week-report/projects")
    public UnifiedResponse<Page<PersonProjectDTO>> projects(@RequestParam(value = "projectName", required = false) String projectName,
                                                            @RequestParam("pageNo") Integer pageNo,
                                                            @RequestParam("pageSize") Integer pageSize){
        String projectNameLike = null;
        if (UtilValidate.isNotEmpty(projectName)) {
            projectNameLike = "%" + projectName + "%";
        }
        return UnifiedResponse.ok(weekReportEntityService.findPersonProjects(null, projectNameLike, pageNo, pageSize));
    }

}
